package com.xjl.example.aqs;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * Created by xiaojinlu1990@163.com on 2019/11/30.
 * CyclicBarrier 可循环调用的方法  重要的方法 （适用场景：用于并行计算）
 * 1 await等待到对应的线程数之后就开始执行剩下的操作
 * 2
 * 3
 *
 */
public class CyclicBarrierExmaple {

    private static Logger log = LoggerFactory.getLogger(CyclicBarrierExmaple.class);

    public final static int clienttotal = 30;
    public final static int threadTotal = 200;
    static CyclicBarrier cyclicBarrier =new  CyclicBarrier(5);


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < clienttotal; i++) {

            final int count = i;
            Thread.sleep(1000);
            executor.execute(() ->{
                try {
                    add(count);
                }catch (Exception e){
                    log.info("{}",e.getStackTrace());
                }
            });
        }
        log.info("finish!!!");
        executor.shutdown();
    }

    private static void add(int count) {
        try {
            cyclicBarrier.await();
            Thread.sleep(1000);
            log.info("{}",count);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
